﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FySystem.Job.JobTask
{
    /// <summary>
    /// 按照指定的时间间隔来执行定时任务，单位s，最小单位1s
    /// </summary>
    public class IntervalJob : JobBase
    {
        public int Interval { get; private set; }

        /// <summary>
        /// 按照指定的时间间隔来执行定时任务，单位s，最小单位1s
        /// </summary>
        /// <param name="jobName"></param>
        /// <param name="jobExecuter"></param>
        /// <param name="interval">执行间隔时间，单位s</param>
        public IntervalJob(string jobName, FyJobContext.FyJobAction jobExecuter, int interval) : base(jobName, jobExecuter)
        {
            try
            {
                if (interval <= 0)
                    throw new Exception("interval必须大于0~");

                Interval = interval * 1000;

                //初始化
                InitializeJob();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void InitializeJob()
        {
            try
            {
                //是否执行
                ExecuteTrigger = job =>
                {
                    bool res = false;
                    try
                    {
                        if (DateTime.Now >= NextExecuteTime)
                            res = true;
                    }
                    catch { }
                    return res;
                };

                //下次执行时间
                NextExecuteTimeGenerator = job =>
                {
                    DateTime res = DateTime.MaxValue;
                    try
                    {
                        res = DateTime.Now.AddMilliseconds(Interval);
                    }
                    catch { }
                    return res;
                };
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
